package com.lonely.fx.bind;

import javafx.application.Application;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.SimpleListProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

/**
 * @date: 2022-07-24 19:20
 * @author: ztkj-hzb
 * @description:
 **/
public class ValueAt案例 extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {

        VBox vBox = new VBox();

        HBox hBox = new HBox();

        TextField textField1 = new TextField();
        TextField textField2 = new TextField();
        hBox.getChildren().addAll(textField1, textField2);


        ObservableList<String> list = FXCollections.observableArrayList();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        SimpleListProperty<String> listProperty = new SimpleListProperty<>(list);

        //准备列表数据
        VBox listData = new VBox();
        for (int i = 0; i < listProperty.size(); i++) {
            Label label = new Label(listProperty.get(i));
            label.setFont(Font.font(20));
            ObjectBinding<String> valueAt = listProperty.valueAt(i);
            label.textProperty().bind(valueAt);
            listData.getChildren().add(label);
        }


        /**
         * 点击确定按钮，修改列表数据
         */
        textField2.textProperty().addListener((observable, oldValue, newValue) -> {
            if (textField1.getText() == null || "".equals(textField1.getText())) {
                return;
            }
            int index = Integer.parseInt(textField1.getText());
            listProperty.set(index, newValue);
        });


        vBox.getChildren().addAll(hBox, listData);
        primaryStage.setScene(new Scene(vBox));
        primaryStage.setWidth(600);
        primaryStage.setHeight(500);
        primaryStage.show();
    }
}
